from rest_framework import serializers
from django_redis import get_redis_connection
from rest_framework_jwt.settings import api_settings
from django.core.mail import send_mail
from django.conf import settings
from users.models import User, Address
import re

class AddressTitleSerializer(serializers.ModelSerializer):
    """
    地址标题
    """
    class Meta:
        model = Address
        fields = ('title',)

class UserAddrSerializer(serializers.ModelSerializer):
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')

    def create(self, validated_data):
        # Address模型类中有user属性,将user对象添加到模型类的创建参数中
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)


class SendMailViewSerialize(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'email')
        extra_kwargs = {
            'email': {
                'required': True
            }
        }

    def update(self, instance, validated_data):
        """发送邮件"""
        # 更新邮件
        instance.email = validated_data.get('email')
        instance.save()

        # 发送邮件

        # 设置参数
        # 主题
        subject = '激活邮件'
        # 正文
        message = ''
        # 发送者邮箱
        from_email = settings.EMAIL_FROM
        # 接受邮箱
        recipient_list = [instance.email]

        verify_url = instance.set_active_url()
        html_message = '<p>尊敬的用户您好！</p>' \
                       '<p>感谢您使用美多商城。</p>' \
                       '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
                       '<p><a href="%s">%s<a></p>' % (instance.email, verify_url, verify_url)

        from celery_tasks.mail.tasks import send_active_email

        send_active_email.delay(subject, message, from_email, recipient_list, html_message)

        return instance


class UserInfoDetailViewSerializer(serializers.ModelSerializer):
    """用户详情信息"""

    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email', 'email_active')


class RegisterCreateSerializer(serializers.ModelSerializer):
    # 用户再进行提交的时候有3个数据:校验密码,短信验证码,是否同意协议
    # 所以,我们需要定义三个字段
    password2 = serializers.CharField(label='校验密码', allow_null=False, allow_blank=False, write_only=True)
    sms_code = serializers.CharField(label='短信验证码', max_length=6, min_length=6, allow_null=False, allow_blank=False,
                                     write_only=True)
    allow = serializers.CharField(label='是否同意协议', allow_null=False, allow_blank=False, write_only=True)

    token = serializers.CharField(label='登录状态token', read_only=True)  # 增加token字段

    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'mobile', 'password2', 'sms_code', 'allow', 'token')
        extra_kwargs = {
            'id': {'read_only': True},
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    # 校验手机号码是否合法
    def validate_moblie(self, value):
        if not re.match(r'1[345789]\d{9}', value):
            raise serializers.ValidationError('手机号码不合法')
        return value

    # 校验用户是否勾选协议
    def validate_allow(self, value):
        if value != 'true':
            raise serializers.ValidationError('请勾选同意协议!')
        return value

    # 校验两次密码是否一直,校验短信验证码
    def validate(self, attrs):
        # 获取两次密码
        password = attrs.get('password')
        password2 = attrs.get('password2')
        # 判断两次密码是否一直
        if password != password2:
            raise serializers.ValidationError('两次密码不一致')

        # 创建redis连接
        redis_conn = get_redis_connection('code')
        # 获取短信验证码
        mobile = attrs.get('mobile')
        redis_code = redis_conn.get('sms_%s' % mobile)

        # 判断是否过期
        if not redis_code:
            raise serializers.ValidationError('短信验证码过期')

        # 获取用户短信验证码
        sms_code = attrs.get('sms_code')
        # 判断验证码是否正确
        if sms_code != redis_code.decode():
            raise serializers.ValidationError('短信验证码不正确')
        return attrs

    def create(self, validated_data):

        # 删除不需要的字段
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']
        # 执行保存
        user = super().create(validated_data)
        # 密码加密
        user.set_password(user.password)
        user.save()

        # 补充生成记录登录状态的token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token

        return user
